/*
 *  getoccupier.h
 *  UnixSysPro
 *
 *  Created by ? ? on 07-8-24.
 *  Copyright 2007 __MyCompanyName__. All rights reserved.
 *
 */

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

#define NAMELENGTH 41

 // char *getoccupier(int roomno);

char namebuf[NAMELENGTH];			// buffer to hold name
int infile = -1;					// will hold fild descriptor

char *getoccupier(int roomno)
{
	off_t offset;
	ssize_t nread;
	
	// open the file first time around
	if(infile == -1 &&
	   (infile = open("residents",O_RDONLY) == -1))
	{
		printf("error: can not open residents\n");
		return(NULL);
	}
	
	offset = (roomno - 1)*NAMELENGTH;
	
	// find room slot and read occupier's name
	if(lseek(infile,offset,SEEK_SET) == -1)
	{
		close(infile);
		return(NULL);
	}
	
	if((nread = read(infile,namebuf,NAMELENGTH)) <= 0)
	{
		close(infile);
		return(NULL);
	}	
	// create a string by replacing the newline character
	// with the null terminator
	namebuf[nread - 1] = '\0';
	
	close(infile);
	printf("getoccupier successful\n");
	return namebuf;
		
}
